package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户对象解析器
 * 将 cookie 中 token 值解析成 UserInfo 对象，并注入到请求映射方法参数中
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    // 作用：表示该解析器支持解析的参数类型，此处支持的 UserInfo 类型
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        // true 表示支持对应类型，false 表示不支持
        return methodParameter.hasParameterAnnotation(UserParam.class) && methodParameter.getParameterType() == UserInfo.class;
    }

    // supportsParameter 返回 true,表示该解析器启动了，需要解析对应参数，执行以下方法
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = CookieUtil.getCookie(request);
        if(token == null){
            return null;
        }
        UserInfo userInfo = userInfoRedisService.getUserInfoByToken(token);
        return userInfo;
    }

}
